package com.lzp.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.lzp.common.R;
import com.lzp.gateway.properties.AuthorProperties;
import com.lzp.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class AuthorFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AuthorProperties properties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        List<String> whiteList = properties.getWhites();
        String path = request.getURI().getPath();
        if(whiteList.contains(path)){
            return chain.filter(exchange);
        }
        List<String> authorization = request.getHeaders().get("Authorization");
        String s = authorization.get(0);
        String jwt_token = s.substring(7);      // 值以Bearer 开头
        Claims claims = JwtUtils.parseToken(jwt_token);
        String uuid = claims.get("token").toString();
        String key = "login-token:" + uuid;
        if(redisTemplate.hasKey(key)){
            return chain.filter(exchange);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String msg = "用户不合法！";
        R result = R.error(HttpStatus.UNAUTHORIZED.value(),msg);  //HttpStatus.UNAUTHORIZED.value() == 401
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
